<template>
  <div>
    <a-descriptions bordered size="small">
      <a-descriptions-item label="申请单号" :span="3">
        {{ paymentDetails.applyNo }}
        <span class="status">
          {{ paymentDetails.status | enumValueByKey($const.EXAMINE_TYPE) }}
        </span>
      </a-descriptions-item>
      <!-- <a-descriptions-item label="申办方"> {{ paymentDetails.sponsorName }} </a-descriptions-item> -->
      <a-descriptions-item label="项目编号"> {{ paymentDetails.projectNo }} </a-descriptions-item>
      <a-descriptions-item label="site编号" :span="(paymentDetails && paymentDetails.type == this.$const.SUBJECTANDREESA.DAISHENGPI.value) ? 2 : 1"> {{ paymentDetails.orgNo }} </a-descriptions-item>
      <a-descriptions-item label="访视版本" v-if="paymentDetails && paymentDetails.type != this.$const.SUBJECTANDREESA.DAISHENGPI.value"> {{ versionName || '' }} </a-descriptions-item>
      <a-descriptions-item label="付款类型"> {{ paymentDetails.type | enumValueByKey($const.SUBJECTANDREESA) }} </a-descriptions-item>
      <a-descriptions-item label="收款人员" v-if="isShow"> {{ paymentDetails.type == this.$const.SUBJECTANDREESA.DAISHENGPI.value ? paymentDetails.researchDetailName : paymentDetails.ptsName }} </a-descriptions-item>
      <a-descriptions-item label="收款人员编号" v-else> {{ paymentDetails.type == this.$const.SUBJECTANDREESA.DAISHENGPI.value ? paymentDetails.researchDetailNo : paymentDetails.ptsNo }} </a-descriptions-item>
      <a-descriptions-item label="收款账号" v-if="isShow">
        <span>{{ paymentDetails.bankName || '' }}</span>
        <span>{{ paymentDetails.bankNo | cardNoDeal }}</span>
      </a-descriptions-item>
      <a-descriptions-item label="申请金额"> {{ paymentDetails.totalAmount }} </a-descriptions-item>
      <a-descriptions-item label="当前状态"> {{ paymentDetails.status | enumValueByKey($const.EXAMINE_TYPE) }} </a-descriptions-item>
      <a-descriptions-item label="支付单号"> {{ paymentDetails.payNo }} </a-descriptions-item>
    </a-descriptions>
    <!-- 费用明细 -->
    <a-descriptions title="费用明细" style="margin-top: 20px"></a-descriptions>
    <a-table
      ref="table"
      size="default"
      bordered
      :row-key="record => record.id"
      :pagination="false"
      :data-source="originDetail.detailList"
    >
      <a-table-column title="序号" key="id" data-index="id">
        <template slot-scope="text, row, index">{{ index + 1 }}</template>
      </a-table-column>
      <a-table-column title="报销类目" key="applyType" data-index="applyType" />
      <a-table-column title="访视阶段" key="visitRecordInfo" data-index="visitRecordInfo" v-if="paymentDetails.type === 2"></a-table-column>
      <a-table-column title="发生日期" key="happenDate" data-index="happenDate" v-if="paymentDetails.type === 2">
        <template slot-scope="text, record">
          {{ record.happenDate | moment('YYYY-MM-DD') }}
        </template>
      </a-table-column>
      <a-table-column title="是否默认" key="defaultBool" data-index="defaultBool">
        <template slot-scope="text, row">
          {{ row.defaultBool ? '是' : '否' }}
        </template>
      </a-table-column>
      <a-table-column title="报销金额" key="amount">
        <template slot-scope="text, record">
          <span>￥{{ record.amount }}</span>
          <span v-if="record.defaultAmt" style="margin-left: 40px; color: red">{{ '默认金额：' + record.defaultAmt }}</span>
        </template>
      </a-table-column>
      <a-table-column title="文件" key="fileList">
        <template slot-scope="text, record">
          <!-- 费用文件预览 -->
          <ViewFile v-if="record.fileList.length" :data="record.fileList">
            <a>查看</a>
          </ViewFile>
          <span v-else>无</span>
        </template>
      </a-table-column>
      <a-table-column title="操作" v-if="canAudit">
        <template slot-scope="record">
          <a @click="specialCheck(record)" v-if="isSiteCrc && showSpecialCheck(record)">审批</a>
        </template>
      </a-table-column>
    </a-table>
    <!-- 审批流 -->
    <a-descriptions title="审批流" style="margin-top: 24px;"></a-descriptions>
    <approveSteps :data="originDetail.flowNodeList"></approveSteps>
    <!-- 个税情况 -->
    <a-descriptions title="个税情况" style="margin-top: 20px" v-if="isShowTax">
      <a-descriptions-item label="申请金额"> ￥{{ paymentDetails.totalAmount }} </a-descriptions-item>
      <a-descriptions-item label="个税">
        <span style="margin-right: 10px; width: 5rem;">{{ paymentDetails.personalTax != null ? '￥' + paymentDetails.personalTax : '待处理' }}</span>
      </a-descriptions-item>
      <a-descriptions-item label="预计支付"> ￥{{ (paymentDetails.totalAmount - (paymentDetails.personalTax != null ? paymentDetails.personalTax : 0)).toFixed(2) }} </a-descriptions-item>
    </a-descriptions>
    <p v-if="paymentDetails.taxRemark">备注：{{ paymentDetails.taxRemark }}</p>
    <!-- 申请记录 -->
    <a-descriptions title="申请记录" style="margin-top: 24px;"></a-descriptions>
    <a-steps direction="vertical" :current="costRecords.length - 1" size="small">
      <a-step
        v-for="item in costRecords"
        :status="item.status == $const.FEE_CHECK_STATUS.FAIL.value || item.status == $const.FEE_CHECK_STATUS.REJECT.value ? 'error' : ''"
        :key="item.id"
      >
        <template slot="title">
          {{ item.processTitle === '申报个税' ? '个税办理' : item.processTitle }}
          <span class="red" v-if="!item.children && item.refuseReason">【{{ item.refuseReason }}】</span>
        </template>
        <template slot="description">
          <div v-if="!item.children">
            <span>{{ item.desc }}</span>
            <a v-if="item.processTitle === '申报个税' && item.proofUrl && $options.filters.isPtsVisible()" style="margin-left: 10px" target="_blank" :href="item.proofUrl | dealImageUrl">个税凭证</a>
            <a v-if="item.processTitle === '银行付款' && item.proofUrl && $options.filters.isPtsVisible()" style="margin-left: 10px" target="_blank" :href="item.proofUrl | dealImageUrl">支付凭证</a>
            <a-button v-if="isShowUrgeBtn(item)" type="primary" style="margin-left: 10px" @click="clickQuickStart(item)">催办</a-button>
          </div>
          <template v-else>
            <div v-for="(k, i) in item.children" :key="i">
              {{ k.desc }}
              <span class="red" v-if="k.refuseReason">【{{ k.refuseReason }}】</span>
              <a-button v-if="isShowUrgeBtn(item)" type="primary" style="margin-left: 10px" @click="clickQuickStart(item)">催办</a-button>
            </div>
          </template>
        </template>
      </a-step>
    </a-steps>
    <!-- 费用科目快照 -->
    <a-descriptions title="费用科目快照" style="margin-top: 24px;"></a-descriptions>
    <a-table
      :data-source="originDetail.flowFeeCategoryList"
      :rowKey="record => record.id"
      :pagination="false"
      bordered
    >
      <a-table-column title="申请类目" key="applyType" data-index="applyType"></a-table-column>
      <a-table-column title="是否默认" key="defaulted" data-index="defaulted">
        <template slot-scope="text, row">
          {{ row.defaulted ? '是' : '否' }}
        </template>
      </a-table-column>
      <a-table-column title="默认金额" key="amt" data-index="amt"></a-table-column>
      <a-table-column title="审批资料" key="apv" data-index="apv">
        <template slot-scope="text, row">
          {{ row.apv ? '是' : '否' }}
        </template>
      </a-table-column>
      <a-table-column title="备注" key="remark" data-index="remark"> </a-table-column>
    </a-table>
  </div>
</template>

<script>
import store from '@/store'
import {
  getApplyDetail,
  requestCostUrge,
  getVersionList
} from '@/api/cost/cost'
import moment from 'moment'
import approveSteps from '../overview/detail/responsible/components/approveSteps'
import ViewFile from './researcher/ViewFile'
import { auditSpecial, getSiteCrcByPtsId, getUrgeStatus } from '@/api/cost/audit'
import { getUserNoByIds } from '@/api/account/user'
import { getInfo } from '@/api/login'

export default {
  props: {
    // 是否在弹框内，是的话getInfo在外面操作
    isModal: {
      type: Boolean,
      default: false
    },
    canAudit: {
      type: Boolean,
      default: false
    },
    showUrge: {
      type: Boolean,
      default: false
    },
    costId: [Number, String]
  },
  components: { approveSteps, ViewFile },
  data () {
    return {
      urgeMap: null,
      originDetail: {},
      paymentDetails: {},
      statusList: [
        {
          id: 1,
          name: '状态1'
        },
        {
          id: 2,
          name: '状态2'
        }
      ],
      costRecords: [],
      chekList: [],
      versionName: '',
      isSiteCrc: true, // 是否当前site的CRC，不是CRC的时候不需要这个判段，所以默认是true好一点
      isShow: false, // crc、pi和财务可以看到收款人员和账号，其他角色只能看到收款人员id且看不到账号
      isFinance: 0 // 个税凭证和支付只有财务可以看到
    }
  },
  computed: {
    isShowTax () {
      // 审核通过后，个税没有办理的情况下，其他非财务角色查看审核记录，不能查看个税情况
      if (!this.$store.state.user.roles[0]) return false
      if (this.$store.state.user.roles[0].code !== 'SYS_FINANCE' && this.paymentDetails.personalTax == null) return false
      return this.paymentDetails.status === this.$const.EXAMINE_TYPE.PASSTAX.value || this.paymentDetails.personalTax != null
    }
  },
  mounted () {
    this.$nextTick(() => {
      window.scroll({ top: 0, left: 0 })
    })
    this.checkRole()
    !this.isModal && this.getInfo()
  },
  methods: {
    async getUserRole (proId) {
      const res = await getInfo({ proId })
      this.$store.commit('SET_ROLES', res.roles)
      this.$store.commit('SET_INFO', res.user)
      this.$store.commit('SET_PMS', res.pms)
    },
    showSpecialCheck (row) {
      return this.chekList.some(v => v.proFeeApplyDetailId === row.id && v.needCheck)
    },
    async specialCheck (row) {
      const req = {
        id: this.paymentDetails.id,
        detailId: row.id,
        applyType: row.applyType,
        status: '',
        refuseReason: ''
      }
      this.$confirm({
        title: '确认同意审批吗',
        okText: '同意',
        cancelText: '拒绝',
        closable: true,
        maskClosable: true,
        content: h => <textarea id="feeDetailRefuseReason" placeholder="审批理由" style="width: 100%;padding: 5px;" />,
        onOk: async () => {
          req.status = 1
          await auditSpecial(req)
          this.$message.success('操作成功')
          await this.getInfo()
          this.$emit('refresh')
        },
        onCancel: async (e) => {
          if (e.triggerCancel) return
          req.status = -1
          req.refuseReason = document.getElementById('feeDetailRefuseReason').value
          if (!req.refuseReason) {
            this.$message.warning('请填写拒绝理由')
            return
          }
          await auditSpecial(req)
          this.$message.success('操作成功')
          await this.getInfo()
          this.$emit('refresh')
        }
      })
    },
    getCheckList () {
      const needCheckNodeList = this.originDetail.processList.filter(v => v.resultOrAction === 2 && v.proFlowNodeCode.slice(3) !== '0000')
      this.chekList = needCheckNodeList.map(v => {
        let needCheck
        const isRole = this.$store.state.user.roles[0].code === v.roleCode
        // 到人
        if (v.processType === 1) {
          needCheck = v.processorId.split(',').includes(String(this.$store.state.user.info.id))
        } else {
          needCheck = isRole
        }
        return {
          ...v,
          needCheck
        }
      })
    },
    checkUrge (item) {
      if (!this.showUrge) return false
      // 待处理
      return item.resultOrAction === 2 && this.paymentDetails.createrId === store.getters.userInfo.id
    },
    // 催办
    clickQuickStart (row) {
      if (!this.urgeMap[row.id]) return this.$message.warning('已经有人催过了，改天再试')
      requestCostUrge({
        id: this.costId,
        processId: row.id
      }).then(res => {
        this.urgeMap[row.id] = false
        this.$message.success('催办成功')
      })
    },
    // 判断角色
    checkRole () {
      this.isShow = this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.CRC.value) || this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.PI.value) || this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.FINANCE.value) ? 1 : 0
      this.isFinance = this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.FINANCE.value) ? 1 : 0
    },
    getUserCode (ids, list) {
      const res = ids.split(',').map(v => {
        const user = list.find(item => item.id === +v)
        return user ? user.userNo : ''
      }).filter(Boolean).toString()
      return res ? '-' + res : ''
    },
    async getInfo () {
      // 获取详情
      const res = await getApplyDetail({ id: this.costId })
      const that = this
      this.costRecords = []
      this.originDetail = res
      const { processList } = res
      this.paymentDetails = res.feeApplyDto
      await this.getUserRole(res.feeApplyDto.proId)
      await this.getIsSiteCrc()
      this.$emit('init', res.feeApplyDto, processList, this.isSiteCrc)
      const needUrgeData = []
      if (processList && processList.length) {
        const processors = processList.flatMap(process => {
          if (!process.processorId) return []
          return process.processorId.split(',')
        })

        const userCodeList = await getUserNoByIds({ ids: processors.toString(), proId: res.feeApplyDto.proId })
        // 处理主节点
        // eslint-disable-next-line
        function dealItem (item) {
          let desc = `${moment(item.processTime).format('YYYY-MM-DD HH:mm:ss')} `
          if (item.processTitle === '银行付款') {
            if (item.status === 7) {
              desc += `完成支付 支付单号${res.feeApplyDto.payNo} 【完成】`
            } else if (item.status === -2) {
              desc += `支付失败，失败原因：${item.refuseReason}`
            }
          } else if (item.processorId) {
            const userCode = item.roleCode === 'Investigator' ? `-${item.processorNo}` : that.getUserCode(item.processorId, userCodeList)
            if (item.processTitle === '申报个税') {
              if (res.feeApplyDto.personalTax === 0 || res.feeApplyDto.personalTax == null) {
                desc += `${item.roleName}${userCode} 无需办理，个税金额为 ￥0 【${that.$options.filters.enumValueByKey(item.status, that.$const.FEE_CHECK_STATUS)}】`
              } else {
                desc += `${item.roleName}${userCode} 已完成个税办理，个税金额为 ￥${res.feeApplyDto.personalTax} 【${that.$options.filters.enumValueByKey(item.status, that.$const.FEE_CHECK_STATUS)}】`
              }
            } else {
              desc += `${item.roleName}${userCode} 【${that.$options.filters.enumValueByKey(item.status, that.$const.FEE_CHECK_STATUS)}】`
            }
          }
          return {
            ...item,
            desc: item.resultOrAction === 2
              ? item.content
              : desc
          }
        }
        // 处理特批节点
        // eslint-disable-next-line
        function dealNodeItem (item) {
          const userCode = item.roleCode === 'Investigator' ? item.processorNo : that.getUserCode(item.processorId, userCodeList)
          const processor = userCode || ''
          const processTime = item.processTime ? moment(item.processTime).format('YYYY-MM-DD HH:mm:ss') : ''
          return {
            ...item,
            desc: `${processTime} ${item.applyType} 由 ${item.roleName}${processor} 【${that.$options.filters.enumValueByKey(item.status, that.$const.FEE_CHECK_STATUS)}】`
          }
        }

        let condition = null
        processList.forEach((item, i) => {
          if (!item.showInFront) return
          if (this.checkUrge(item)) {
            needUrgeData.push({
              id: item.proFeeApplyId,
              processId: item.id
            })
          }
          // 找到条件节点
          const isCNode = res.flowNodeList.some(v => v.code === item.proFlowNodeCode && v.nodeType === 2)
          if (isCNode) {
            condition = item
          } else {
            if (condition && item.proFlowNodeCode.slice(3) !== '0000') {
              // 将子节点数据结构改为树形
              if (!condition.children) condition.children = []
              condition.children.push(dealNodeItem(item))
              if (condition && i === processList.length - 1) {
                this.costRecords.push(condition)
              }
            } else {
              condition && this.costRecords.push(condition)
              condition = null
              this.costRecords.push(dealItem(item))
            }
          }
        })
      }
      this.paymentDetails.type === 2 && this.getVersionList(this.paymentDetails)
      this.getCheckList()
      this.getNeedUrgeData(needUrgeData)
    },
    async getIsSiteCrc () {
      if (this.paymentDetails.type !== 2) return
      if (!this.$store.state.user.roles) return
      if (this.$store.state.user.roles[0].code !== 'CRC') return
      const crcId = await getSiteCrcByPtsId({
        proId: this.paymentDetails.proId,
        ptsId: this.paymentDetails.ptsId
      })
      this.isSiteCrc = crcId === this.$store.state.user.info.id
    },
    getVersionList ({ proId, visitId }) {
      getVersionList({ proId }).then(res => {
        res.forEach(item => {
          if (item.id === visitId) {
            this.versionName = item.name
          }
        })
      })
    },
    // 获取列表所有的id，一次性去请求是否需要催办
    async getNeedUrgeData (needUrgeData) {
      const map = {}
      for (const val of needUrgeData) {
        map[val.processId] = await getUrgeStatus(val)
      }
      this.urgeMap = map
    },
    isShowUrgeBtn (row) {
      if (row.processTitle === '研究者补充资料') return false
      return this.urgeMap && this.urgeMap[row.id] !== undefined
    }
  },
  beforeDestroy () {
    if (this.$route.path === '/message') {
      this.$store.dispatch('ClearProject')
    }
  }
}
</script>
<style scoped lang="less">
.status {
  margin: 0 20px;
  padding: 3px 10px;
  border: 1px solid #70b603;
  border-radius: 40px;
  color: #70b603;
}
.red {
  color: #e04b28;
}
</style>
